﻿using AutoMapper;
using B.S.Backtrack.Domain.Entities;
using B.S.Backtrack.ErrorCode;
using B.S.Backtrack.Infrastructure.Interface;
using B.S.Backtrack.Read.API.Application.Command.Product;
using B.S.Backtrack.Read.API.Dtos;
using MediatR;

namespace B.S.Backtrack.Read.API.Application.CommandHandler.Product
{
    public class QueryProductHandler : IRequestHandler<QueryProductCommand, ApiPaging<ProductsDTO>>
    {
        private readonly IBaseRepository<Products> proRep;
        private readonly IBaseRepository<Goods> gRep;
        private readonly IMapper mapper;

        public QueryProductHandler(IBaseRepository<Products> proRep,IBaseRepository<Goods> gRep,IMapper mapper)
        {
            this.proRep = proRep;
            this.gRep = gRep;
            this.mapper = mapper;
        }
        public Task<ApiPaging<ProductsDTO>> Handle(QueryProductCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<ProductsDTO> result = new ApiPaging<ProductsDTO>();
            var list = from a in proRep.GetAll()
                       join b in gRep.GetAll() on a.GoodId equals b.GoodId
                       where a.IsDel==false
                       select new ProductsDTO
                       {
                           ProductId = a.ProductId,
                           GoodId = a.GoodId,
                           GoodName = b.GoodName,
                           IsDel = a.IsDel,
                           PictureId = a.PictureId,
                           ProductionBatch = a.ProductionBatch,
                           ProductionNum = a.ProductionNum,
                           ProductionEnterprise = a.ProductionEnterprise,
                           ShelfLife = a.ShelfLife,
                            GoverImage = a.GoverImage,

                       };
            if (!string.IsNullOrEmpty(request.GoodName))
            {
                list = list.Where(c => c.GoodName.Contains(request.GoodName));
            }
            result.TotalCount = list.Count();
            result.TotalPage= (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            list=list.OrderByDescending(x=>x.ProductId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            result.Code = ApiEnums.查询成功;
            result.Msg=ApiEnums.查询成功.ToString();
            result.Items=mapper.Map<List<ProductsDTO>>(list);
            return Task.FromResult(result);
        }
    }
}
